package fileProcessing.PreprocessingAnalysis;

import java.util.ArrayList;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LineDensity {
	private ArrayList<LineDensityStruct> densityList = new ArrayList<LineDensityStruct>(500);
	private String fields = 
			"((suffix)|(zip\\s*code)|(postal\\s*code)|(address)|(bank\\s*account)|(bank\\s*account)"+
			"(card\\s*number)|(credit\\s*card)|(card\\s*type)|(card)|(city)|(coutry)|(cvv)|(security\\s*code)"+
			"(date)|(issued)|(birth)|(dob)|(state)|(license)|(mail)|(expir)|(organization)|(business)|(company)"+
			"(psswrd)|(pass)|(name)|(phone)|(PIN)|(personal\\s*i)|(routing\\s*number)|(security\\s*question)"+
			"(ssn)|(social\\s*sec)|(url)|(website)|(host)|(application))";
	private int totalFileFieldHits = 0;
	
	public class LineDensityStruct{
		protected int lineHits;
		protected double lineDensity;//lineDensity = lineCount/totalFieldHits
		public LineDensityStruct(int num){
			lineHits = num;
		}
		
		public void calcLineDensity(int totalHits){
			lineDensity  = (double)lineHits/(double)totalHits;
		}
		
		public double getDensity(){
			return lineDensity;
		}
	}
	
	public ArrayList<LineDensityStruct> inFile(Scanner inFile){
		densityList.clear();
		int line = 0;
		totalFileFieldHits = 0;
		while(inFile.hasNext()){
			line++;
			determineLineDensity(line,inFile.nextLine());
		}
		calculateLineDensities();
		return densityList;
	}
	
	public void calculateLineDensities(){
		for(LineDensityStruct line : densityList){
			line.calcLineDensity(totalFileFieldHits);
		}
	}
	
	public void determineLineDensity(int lineNumber,String line){
		System.out.println(lineNumber);
		int lineDensity = fieldCount(line);
		totalFileFieldHits+=lineDensity;
		LineDensityStruct currDens = new LineDensityStruct(lineDensity);
		densityList.add(currDens);
	}
	
	/**
	 * This method counts the actual number of occurrences per line the field keywords are found.
	 * @param input
	 * @return
	 */
	public int fieldCount(String input){
		Pattern fieldPattern;
		Matcher fieldMatcher;
		int count = 0, matchLength = 0;
		fieldPattern = Pattern.compile(fields+"(.+)",Pattern.CASE_INSENSITIVE);
		fieldMatcher = fieldPattern.matcher(input);
			
			while(fieldMatcher.find()){
				count++;
				matchLength += fieldMatcher.group(1).length();
				if(fieldMatcher.group(3) != null)
					fieldPattern.matcher(fieldMatcher.group(3));
			}
			System.out.println(count);
		return count;
	}
	
	public String getFields(){
		return fields;
	}
}
